package cn.pconline.autoclub.task;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pconline.autoclub.task.util.ApiException;
import cn.pconline.autoclub.task.util.TokenUtils;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class CloudLogTask {
	private static Logger log = LoggerFactory.getLogger(CloudLogTask.class);
	
	private String logSql = "select cloud_log_id, user_id,club_id,club_name,type from ac_cloud_club_log where status <= 0";
	public static void main(String[] args) throws SQLException{
		AppUtils.initLog(CloudLogTask.class);
		CloudLogTask task = new CloudLogTask();
		List<CloudLog> logs=task.getLog();
		task.synRongCloud(logs);
	}
	
	/**
	 * 查询日志
	 * @param type
	 * @return
	 * @throws SQLException
	 */
	public  List<CloudLog> getLog() throws SQLException{
		List<CloudLog> list = new ArrayList<CloudLog>();
		Connection conn = DBUtils.getConnection();
		PreparedStatement ps;
	    ResultSet rs;
	    ps = conn.prepareStatement(logSql);
        rs = ps.executeQuery();
        while (rs.next()) {
        	long logId = rs.getLong("cloud_log_id");
			long userId=rs.getLong("user_id");
			long clubId = rs.getLong("club_id");
			String clubName = rs.getString("club_name");
			int type = rs.getInt("type");
			CloudLog cLog = new CloudLog();
			cLog.setCloudLogId(logId);
			cLog.setUserId(userId);
			cLog.setClubId(clubId);
			cLog.setClubName(clubName);
			cLog.setType(type);
			list.add(cLog);
		}
        DBUtils.releaseConn(conn, ps, rs);
        return list;
	}
	
	public void synRongCloud(List<CloudLog> list){
		 if(list==null || list.isEmpty()){
			 log.info("There is no CloudLog to synchronize");
			 return;
		 }
         Connection conn = DBUtils.getConnection();
         PreparedStatement ps = null;
         boolean oldCommit = DBUtils.getAutoCommitValue(conn);
         int successCount = 0;
         try{
         conn.setAutoCommit(false);
         //推送成功一条，数据库update一条，每条数据不相干,数据量不大，不考虑批处理
			 for (int i=0;i<list.size();i++) {
				CloudLog clog = list.get(i);
				String userId_s = String.valueOf(clog.getUserId());
	            String clubId_s = String.valueOf(clog.getClubId());
	            int count = 0;
	            boolean flag = false;
				try {
					if(clog.getType()==CloudLog.JOIN_CLOUD){		//加入融云
						flag =TokenUtils.joinClub(userId_s, clubId_s, clog.getClubName());
					}else if(clog.getType()==CloudLog.QUIT_CLOUD){	//退出融云
						flag = TokenUtils.QuitClub(userId_s, clubId_s);
					}
					   
				} catch (ApiException e) {
					e.printStackTrace();
					log.error("synRongCloud throws ApiException: userId:{} ,clubId :{}",userId_s,clubId_s);
				}
				if(flag){
					successCount++;
					//推送成功 ，删除记录
					clog.setStatus(CloudLog.SUCCESS_SEND);
					String delSQL = "delete from ac_cloud_club_log where cloud_log_id = ?";
					ps = conn.prepareStatement(delSQL);
					ps.setLong(1, clog.getCloudLogId());
					count = ps.executeUpdate();
					conn.commit();
				}else{
					//推送失败 ，修改状态
					clog.setStatus(CloudLog.FAIL_SEND);
					String updateSQL = "update ac_cloud_club_log set status = ? ,update_at = ? where cloud_log_id = ? ";
					ps = conn.prepareStatement(updateSQL);
					ps.setInt(1, clog.getStatus());
			        ps.setString(2,DateUtils.format(DateUtils.getNow(), "yyyy-MM-dd HH:mm:ss") );
			        ps.setLong(3, clog.getCloudLogId());
			        count = ps.executeUpdate();
			        conn.commit();
	//				ps.execute();
				}
				if(count==0){
					log.warn("can't find cloudlog to send cloudLogId :{}",clog.getCloudLogId());
				}
			 }
			 log.info("融云同步成功 ，一共同步了 {} 条记录",successCount);
		 }catch (SQLException e) {
				e.printStackTrace();
		 }finally{
			 try {
				conn.setAutoCommit(oldCommit);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			 DBUtils.releaseConn(conn, ps, null);
		 }
	}
}
class CloudLog{
	/**加入融云**/
	public static final int JOIN_CLOUD = 1;
	/**退出融云**/
	public static final int QUIT_CLOUD = 2;
	
	/**发送失败**/
	public static final int FAIL_SEND = -1;
	/**未发送**/
	public static final int NOT_SEND = 0;
	/**发送成功**/
	public static final int SUCCESS_SEND = 1;
	
	private long cloudLogId;	//融云日志id
	private int type;			//类型，1 加入融云，2 退出融云
	private long userId;		//用户id
	private long clubId;		//车友会id
	private String clubName;   //车友会名称
	private Date createAt;		//创建时间
	private Date updateAt;		//更新时间
	private int status;		//状态，-1>发送失败 ，0>未发送，1>发送完成
	
	public long getCloudLogId() {
		return cloudLogId;
	}
	public void setCloudLogId(long cloudLogId) {
		this.cloudLogId = cloudLogId;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public long getUserId() {
		return userId;
	}
	public void setUserId(long userId) {
		this.userId = userId;
	}
	public long getClubId() {
		return clubId;
	}
	public void setClubId(long clubId) {
		this.clubId = clubId;
	}
	public String getClubName() {
		return clubName;
	}
	public void setClubName(String clubName) {
		this.clubName = clubName;
	}
	public Date getCreateAt() {
		return createAt;
	}
	public void setCreateAt(Date createAt) {
		this.createAt = createAt;
	}
	public Date getUpdateAt() {
		return updateAt;
	}
	public void setUpdateAt(Date updateAt) {
		this.updateAt = updateAt;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	
}
